package com.fxu.framework.mq.redis.streams;

import com.fxu.framework.core.holder.RedisHolder;
import com.fxu.framework.core.holder.SpringHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.connection.stream.Record;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 单例模式获取 redisTemplate
 * @author fangxu
 * @version 1.0.0
 */
@Slf4j
@Component("redisStreamsHolder")
public class RedisStreamsHolder {
    private static RedisStreamsHolder holder = null;
    public synchronized static RedisStreamsHolder getHolder() {
        if (holder == null) {
            holder = SpringHolder.getBean("redisStreamsHolder");
        }
        return holder;
    }

    public RecordId sendMessage(String streamKey, Map<String, String> message) {
        // 使用 MapRecord 创建记录
        MapRecord<String, String, String> record = StreamRecords.mapBacked(message).withStreamKey(streamKey);
        return RedisHolder.getRedisTemplate().opsForStream().add(record);
    }

    public String addMap(String streamKey, Map<String, String> value){
        return RedisHolder.getRedisTemplate().opsForStream().add(streamKey, value).getValue();
    }

    public String addRecord(Record<String, Object> record){
        return RedisHolder.getRedisTemplate().opsForStream().add(record).getValue();
    }

    public Long ack(String streamKey, String group, String ... recordIds){
        return RedisHolder.getRedisTemplate().opsForStream().acknowledge(streamKey, group, recordIds);
    }

    public Long del(String streamKey, String ... recordIds){
        return RedisHolder.getRedisTemplate().opsForStream().delete(streamKey, recordIds);
    }
}